{% extends "base.html" %}

{% block title %}使用提示词 - {{ prompt.title }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="bi bi-play-circle"></i> 使用提示词</h2>
                <a href="{{ url_for('prompts') }}" class="btn btn-secondary">
                    <i class="bi bi-arrow-left"></i> 返回列表
                </a>
            </div>

            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">{{ prompt.title }}</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>原始内容：</h6>
                            <div class="border p-3 mb-3" style="background-color: #f8f9fa;">
                                <pre>{{ prompt.content }}</pre>
                            </div>
                            
                            <div id="variables-section" style="display: none;">
                                <h6>变量替换：</h6>
                                <form id="replace-form">
                                    <div id="variables-container"></div>
                                    <button type="submit" class="btn btn-primary mt-2">
                                        <i class="bi bi-arrow-repeat"></i> 替换变量
                                    </button>
                                </form>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h6>处理后内容：</h6>
                            <div class="border p-3 mb-3" style="background-color: #f0f8ff; min-height: 200px;">
                                <pre id="processed-content">{{ prompt.content }}</pre>
                            </div>
                            
                            <div class="d-flex gap-2">
                                <button id="copy-btn" class="btn btn-success" onclick="copyToClipboard()">
                                    <i class="bi bi-clipboard"></i> 复制内容
                                </button>
                                <button id="clear-btn" class="btn btn-warning" onclick="clearContent()">
                                    <i class="bi bi-arrow-clockwise"></i> 重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 检测变量并显示替换表单
function detectVariables() {
    const content = `{{ prompt.content }}`;
    const variableRegex = /\{\{\s*(\w+)\s*\}\}/g;
    const variables = new Set();
    let match;
    
    while ((match = variableRegex.exec(content)) !== null) {
        variables.add(match[1]);
    }
    
    if (variables.size > 0) {
        document.getElementById('variables-section').style.display = 'block';
        const container = document.getElementById('variables-container');
        container.innerHTML = '';
        
        variables.forEach(variable => {
            const div = document.createElement('div');
            div.className = 'mb-2';
            div.innerHTML = `
                <label class="form-label">${variable}:</label>
                <input type="text" class="form-control" name="${variable}" placeholder="请输入${variable}的值">
            `;
            container.appendChild(div);
        });
    }
}

// 替换变量
document.getElementById('replace-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const variables = {};
    
    for (let [key, value] of formData.entries()) {
        variables[key] = value;
    }
    
    fetch(`/api/prompts/{{ prompt.id }}/replace`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({variables: variables})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('processed-content').textContent = data.content;
        } else {
            alert('替换失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('请求失败');
    });
});

// 复制到剪贴板
function copyToClipboard() {
    const content = document.getElementById('processed-content').textContent;
    navigator.clipboard.writeText(content).then(() => {
        const btn = document.getElementById('copy-btn');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-check"></i> 已复制';
        btn.classList.remove('btn-success');
        btn.classList.add('btn-success');
        
        setTimeout(() => {
            btn.innerHTML = originalText;
        }, 2000);
    }).catch(err => {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
    });
}

// 重置内容
function clearContent() {
    document.getElementById('processed-content').textContent = `{{ prompt.content }}`;
    document.getElementById('replace-form').reset();
}

// 页面加载时检测变量
document.addEventListener('DOMContentLoaded', detectVariables);
</script>
{% endblock %}